'''
Functions present in an old API and are schedule to deprecation or 
re-implementation. These functions are here because the py-tutor system already
uses them. 
'''
import collections
import functools
from old_query import jpath
from simple_path import jpath_update
from substitutions import *

def copy(obj, convert=True, frozen=False):
    '''Return a copy of JSON object or JSON-serializable object.
    
    Parameters
    ----------
    
    obj : JSON-like structure
        any JSON-like structure
    convert : bool
        If True, tries conversion when it encounter non-standard types. 
        Otherwise, it raises a TypeError
    frozen : bool
        If True, returns a frozen JSON structure, i.e., lists are replaced by
        tuples and dicts are replaced by FrozenDicts
    
    Output
    ------
    
    Returns a normalized copy of 'obj'.
    '''

    C = functools.partial(copy, convert=convert, frozen=frozen)

    if obj is None:
        return None
    elif isinstance(obj, collections.Mapping):
        D = dict if not frozen else frozendict
        return D((k, C(v)) for (k, v) in obj.items())
    elif isinstance(obj, basestring):
        return unicode(obj)
    elif isinstance(obj, collections.Iterable):
        D = list if not frozen else tuple
        return D(C(x) for x in obj)
    elif isinstance(obj, (int, float, long)):
        return obj
    else:
        try:
            serializer = obj._json_
            if not convert:
                raise AttributeError
        except AttributeError:
            raise TypeError('unsupported type, {0}'.format(type(obj)))
        return serializer()
